package com.qing.springcloud.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.codec.Base62;
import com.qing.springcloud.dao.UserDao;
import com.qing.springcloud.dto.user.UserDTO;
import com.qing.springcloud.dto.user.UserRegisterDTO;
import com.qing.springcloud.dto.user.UserUpdateDTO;
import com.qing.springcloud.entity.User;
import com.qing.springcloud.exception.BusinessException;
import com.qing.springcloud.manger.UserChannelManager;
import com.qing.springcloud.model.UserStatus;

import com.qing.springcloud.utils.RedisUtils;
import com.qing.springcloud.utils.UserInfoUtils;
import io.netty.channel.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.qing.springcloud.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 用户表服务接口实现
 *
 * @author zhipeng.cao
 * @since 2025-07-09 20:09:50
 * @description 由 Mybatisplus Code Generator 创建
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class UserServiceImpl implements UserService {
    
    private final UserDao userDao;

    private  final UserInfoUtils userInfoUtils;


    @Override
    public UserDTO register(UserRegisterDTO dto) {
        if (userDao.existsByUsername(dto.getUsername())) {
            throw new BusinessException("用户名已存在");
        }

        User user = new User();
        user.setUsername(dto.getUsername());
        user.setPassword(Base62.encode(dto.getPassword()));
        user.setNickname(dto.getNickname());
        user.setPhone(dto.getPhone());
        userDao.save(user);

        return convertToDTO(user);
    }



    @Override
    public UserDTO getUserInfo() {
        Long userId = StpUtil.getLoginIdAsLong();
        User user = userDao.getById(userId)
                .orElseThrow(() -> new BusinessException("用户不存在"));

        userInfoUtils.setUserInfo(userId,convertToDTO(user));
        return convertToDTO(user);
    }



    @Override
    public void updateUserInfo(UserUpdateDTO dto) {
        User user = userDao.getById(StpUtil.getLoginIdAsLong())
                .orElseThrow(() -> new BusinessException("用户不存在"));

        user.setNickname(dto.getNickname());
        user.setAvatar(dto.getAvatar());
        user.setPhone(dto.getPhone());
        userDao.updateById(user);
    }

    private UserDTO convertToDTO(User user) {
        return UserDTO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .nickname(user.getNickname())
                .avatar(user.getAvatar())
                .lastLogin(user.getLastLogin())
                .build();
    }
}